#include "comm.hpp"

int main()
{
    Log("child pid is ", Debug) << getpid() << std::endl;
    key_t k = ftok(PATH_NAME, PROJ_ID);
    if (k < 0)
    {
        Log("ftok error", Error) << " client key is " << k << std::endl;
    }
    Log("creat key success", Debug) << " client key is " << k << std::endl;
    int shmid = shmget(k, SHM_SIZE, 0);
    if (shmid < 0)
    {
        Log("create shm failed", Error) << "client key is " << k << std::endl;
        exit(1);
    }
    Log("get shm success", Debug) << "client key is " << k << std::endl;

    char *shmaddr = (char *)shmat(shmid, nullptr, 0);
    if (shmaddr == nullptr)
    {
        Log("shmat failed", Error) << "client key is " << k << std::endl;
        exit(2);
    }
    Log("shmat success", Debug) << "client key is " << k << std::endl;

    int fd = OpenFIFO(FIFO_NAME, WRITE);
    if (fd < 0)
    {
        Log("open fifo failed", Error) << "client key is " << k << std::endl;
        exit(3);
    }

    while (true)
    {
        ssize_t s = read(0, shmaddr, SHM_SIZE - 1);
        if (s > 0)
        {
            shmaddr[s-1] = '\0';
            Signal(fd);
            if (strcmp(shmaddr, "quit") == 0)
                break;
        }
    }
    int ret = shmdt(shmaddr);
    if (ret < 0)
    {
        Log("shmdt failed", Error) << "client key is " << k << std::endl;
        exit(4);
    }
    Log("shmdt success", Debug) << "client key is " << k << std::endl;

    return 0;
}